package binarysearch;

/**
 * Created with IntelliJ IDEA.
 * Description: 二分查找基础版
 * User: YJ
 * Date: 2023-9-23
 * Time: 20:52
 */
public class TestBinarySearch {
    public static int binarySearch(int[] arr,int target) {
        int i = 0;
        int j = arr.length - 1;
        while (i <= j) {
            //中间值
            int mid = (i + j) >>> 1;
            if(target < arr[mid]) { //要找的值在 i 与 mid 之间
                j = mid - 1;
            } else if (arr[mid] < target) { //要找的值在 mid 与 j 之间
                i = mid + 1;
            } else { //找到了
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{2,6,18,54,89,96};
        System.out.println(binarySearch(arr, 96));
    }
}
